//
//  KRWebViewCell.m
//  cookBook
//
//  Created by kuroken on 16/1/16.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRWebViewCell.h"
#import <NJKWebViewProgress.h>
#import <RegexKitLite.h>
#import "KRConst.h"

#define KRLog(...)

static NSString * const reuseIdentifier = @"webView";

NSInteger const KRWebViewOffset = 10;

@interface KRWebViewCell () <UIWebViewDelegate, NJKWebViewProgressDelegate>
@property (nonatomic, weak) UIWebView *webView;
@property (nonatomic, copy) NSString *outerHTML;
@property (nonatomic, copy) NSString *js;
@property (nonatomic, assign, getter=hasPosted) BOOL post;

@property (nonatomic, strong) NJKWebViewProgress *progressProxy;
@end

@implementation KRWebViewCell

NJKWebViewProgress *_progressProxy;

+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    KRWebViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[KRWebViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.clipsToBounds = YES;
        
        UIWebView *webView = [[UIWebView alloc] init];
        webView.scrollView.scrollEnabled = NO;
        webView.delegate = self;
        [self.contentView addSubview:webView];
        self.webView = webView;
        
        self.webView.frame = CGRectMake(0, 0, KRScreenWidth, 1);
        self.webView.hidden = YES;
//        self.webView.opaque = NO;
        
        KRLog(@"webView初始值 : %@", NSStringFromCGSize(self.webView.scrollView.contentSize));

        // 初始化JS代码
        [self setupJS];
        
        self.progressProxy = [[NJKWebViewProgress alloc] init];
        self.webView.delegate = self.progressProxy;
        self.progressProxy.webViewProxyDelegate = self;
        self.progressProxy.progressDelegate = self;

    }
    return self;
}

#pragma mark - NJKWebViewProgressDelegate
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    if (progress == 1.0) return;
    if ([self.delegate respondsToSelector:@selector(webViewCellWithProgress:)]) {
        [self.delegate webViewCellWithProgress:progress];
    }
}

/**
 *  初始化JS代码
 */
- (void)setupJS
{
    // JS代码
    NSString *plist = [[NSBundle mainBundle] pathForResource:@"html.plist" ofType:nil];
    NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:plist];
    
    NSMutableString *js = [NSMutableString string];
    [js appendString:[NSString stringWithFormat:@"document.head.innerHTML = \"%@\";", plistDict[@"innerHead"]]];
    [js appendString:@"var bodyHTML = '';"];
    
    [js appendString:[NSString stringWithFormat:@"bodyHTML += \"%@\";", plistDict[@"innerBody1"]]];
    
    [js appendString:@"var jf = document.getElementsByClassName('imit_p box jf')[0];"];
    [js appendString:@"bodyHTML += jf.innerHTML;"];
    [js appendString:@"bodyHTML += '</div></div></div>';"];
    
    [js appendString:[NSString stringWithFormat:@"bodyHTML += \"%@\";", plistDict[@"innerBody2"]]];
    
    [js appendString:@"document.body.innerHTML = bodyHTML;"];
    self.js = js;
}

- (void)setUrl:(NSString *)url
{
    _url = url;

    KRLog(@"%@", url);
    
    if (!self.outerHTML || [self.outerHTML containsPartString:@"default.png"]) {
        if (self.webView.request.URL.absoluteString != nil) return; // 如果正在加载网页，返回
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
    } else {
        [self.webView loadHTMLString:self.outerHTML baseURL:nil];
        
    }
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 过滤多余的请求
    NSString *uselessStr = [request.URL description];

    if ([uselessStr containsPartString:@"baidu"] || [uselessStr containsPartString:@"alicdn"] || [uselessStr containsPartString:@"tanx"]) {
        return NO;
    }
    KRLog(@"request.URL : %@", uselessStr);

#warning TODO 处理点击"超链接和图片"事件
    KRLog(@"-----------------------------");
    KRLog(@"self.url : %@", self.url);
    KRLog(@"request.URL : %@", [request.URL description]); // 正在请求的URL(还未加载)
    KRLog(@"webView.request.URL : %@", webView.request.URL.absoluteString); // 已经请求成功的URL(正在加载)
    
    // 过滤非源URL请求
    if (![[request.URL description] isEqualToString:self.url] && ![webView.request.URL.absoluteString isEqualToString:self.url]) {
        
        NSString *jumpUrl = [request.URL description];
        if ([jumpUrl containsPartString:@"haodourecipe"]) {
            
            NSRange range = [jumpUrl rangeOfString:@"id="];
            NSString *ID = [jumpUrl substringFromIndex:range.length + range.location];

            /* haodourecipe://haodou.com/recipe/info/?id=210823  单条食谱 */

            /* haodourecipe://haodou.com/opentopic/?url=http%3A%2F%2Fgroup.haodou.com%2Ftopic-328039.html&id=328039 单条阅读 */
            
            /*  haodourecipe://haodou.com/user/wo/?id=642281 用户 */

            if ([self.delegate respondsToSelector:@selector(webViewCellWithUrl:ID:)]) {
                [self.delegate webViewCellWithUrl:jumpUrl ID:ID];
            }
        }

        return NO;
    }

    KRLog(@"loading");
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    // 执行JS代码
//    [webView stringByEvaluatingJavaScriptFromString:self.js];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 已经发出通知
    if (self.hasPosted) return;
    
    // 如果self.outerHTML非空，且网页图片非默认图片
    if (self.outerHTML && ![self.outerHTML containsPartString:@"default.png"]) {
        // 只执行一次
        CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
        KRLog(@"webview实际高度 : %f", height);
        [[NSNotificationCenter defaultCenter] postNotificationName:KRWebviewDidGetHeightNotification object:nil userInfo:
         @{KRWebviewHeight : [NSNumber numberWithFloat:height]}];
        
        // 重新设置webView的frame
        self.webView.frame = CGRectMake(0, -KRWebViewOffset, KRScreenWidth, height);
        // 显示webView
        self.webView.hidden = NO;
        self.post = YES;

        return;
    }
    
    // 执行JS代码
    [webView stringByEvaluatingJavaScriptFromString:self.js];
    
    // 获取当前HTML代码
    NSString *currentHTML = [[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].outerHTML;"] description];
    if ([currentHTML containsPartString:@"default.png"])
    {
        // 删除默认图片链接
        self.outerHTML = [self convertURLWithHTMLString:currentHTML];
        [self.webView stopLoading];
        // 加载修改后的html
        [self.webView loadHTMLString:self.outerHTML baseURL:nil];
        
    }
    
}

/*
 <img src="http://www.haodou.com/public/images/rcpForPhone/topic_default.png" original="http://img4.hoto.cn/public/images3/smile/60/112.gif" alt="">
 
 ===>
 
 <img src="http://img4.hoto.cn/public/images3/smile/60/112.gif" alt="">
 */
- (NSString *)convertURLWithHTMLString:(NSString *)html
{
    NSString *pattern = @"<img src=\".*\" original=";
    
    __block NSString *convertedHTML = [NSString string];
    
    [html enumerateStringsSeparatedByRegex:pattern usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
        if (convertedHTML.length) {
            convertedHTML = [convertedHTML stringByAppendingString:@"<img src="];
        }
        convertedHTML = [convertedHTML stringByAppendingString:*capturedStrings];
    }];
    
    return convertedHTML;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


@end
